with sharing public class OverrideCityBudgetNew
{
    public String msg{get;set;}
    public String IdSelect{get;set;}
    public Boolean DisplaySave{get;set;} // display Save button or not
    public Boolean DisplayAdd{get;set;}
    List<Place__c> pList = new  List<Place__c>();
    public CityBudget__c CityBudget{
         get{
             if(CityBudget== null)
                 CityBudget = new CityBudget__c();
             return CityBudget;
         }
         set;
    }
    public List<TableItemControl> AmountBudget{
         get{
             if(AmountBudget== null)
                 AmountBudget= new List<TableItemControl>();
             return AmountBudget;
         }
         set;
    }        
    public List<TableItemControl> AddMoreBudget{ // other city budget
         get{
             if(AddMoreBudget== null)
                 AddMoreBudget= new List<TableItemControl>();
             return AddMoreBudget;
         }
         set;
    }       
    public Sub_Region_Budget__c SRB { 
         get{
             if(SRB == null)
                 SRB = new Sub_Region_Budget__c();
             return SRB ;
         }
         set;
    }        
    public List<TableItemControl> TableItemsDown{         
        get{
             if(TableItemsDown== null)
                 TableItemsDown= new List<TableItemControl>();
             return TableItemsDown;
         }
        set;
    }    
    public String UrlId
    {
        get{        
            return System.currentPageReference().getParameters().get('id');     
           }  
        set;
    }  
    User cu  = [Select Name,UserRoleId,ProfileId,Title__c From User Where Id =:UserInfo.getUserId()];
    UserRole ur = [Select Id,Name,ParentRoleId  From UserRole Where Id =: cu.UserRoleId]; 
    Profile ProfileMarketing = [Select p.Name, p.Id From Profile p Where p.Name =: GlobalProperties.ProfileRMMM ];
    Profile ProfileSRMMM = [Select p.Name, p.Id From Profile p Where p.Name =: GlobalProperties.ProfileSRMMM ];
    Profile ProfileRSM = [Select p.Name, p.Id From Profile p Where p.Name =: GlobalProperties.ProfileRSM_M];
    Profile ProfileRSTM = [Select p.Name, p.Id From Profile p Where p.Name =: GlobalProperties.ProfileRSM_TM];
    Profile ProfileRGM = [Select p.Name, p.Id From Profile p Where p.Name =: GlobalProperties.ProfileRGM];
    
    String SubregionName;
    public OverrideCityBudgetNew(){    
        DisplaySave = true;
        DisplayAdd = true;
        SRB = [Select s.total_score__c, s.potential_score__c, s.final_weighting__c, s.Year__c, s.Total_budget_kg__c, 
            s.Total_budget_RMB__c, s.This_year_PE_Sample_kg__c, s.This_year_In_market_sales_kg__c, 
            s.Submit__c, s.Sub_Region__c, s.Sales_City__c, s.Region__c, s.Rate__c, s.Place__c, s.PE_Sample_Management__c, 
            s.OwnerId, s.Name, s.Line_Manager__c, s.Last_year_sales_weighting__c, s.Last_year_conversion_weighting__c, 
            s.Last_year_PE_Sample_kg__c, s.Last_year_In_market_sales_kg__c,s.Id, s.Area__c, s.ApprovedFormula__c ,s.ApprovalStatusFormula__c 
            From Sub_Region_Budget__c s Where id =: UrlId];
       if(SRB.ApprovalStatusFormula__c != '审批通过') // sub region budget is not allowed.
       {
           msg = '未审批通过';
       }
       else
       {
           List<CityBudget__c> ExistRecord = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.InMarketValueHide__c ,
                c.TotalScore__c, c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c,
                c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c, c.Submit__c,c.ConversionForcast__c,
                c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c, 
                c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c, c.IsDeleted, c.Id, 
                c.FinalWeighting__c,c.Area__c, c.Approved__c,c.CityHead__c From CityBudget__c c Where c.SubRegionBudget__c =: UrlId and Multiple__c =: false];
           
           // exist multiple city head in same city
           List<CityBudget__c> ExistRecordMultiple = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.InMarketValueHide__c,
                c.TotalScore__c, c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c,
                c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c, c.Submit__c,c.ConversionForcast__c,
                c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c, 
                c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c, c.IsDeleted, c.Id, 
                c.FinalWeighting__c,c.Area__c, c.Approved__c,c.CityHead__c From CityBudget__c c Where c.SubRegionBudget__c =: UrlId and Multiple__c =: true];
      
            CityBudget.Year__c = SRB.Year__c;
            CityBudget.Rate__c = SRB.Rate__c;
            CityBudget.TotalBudgetkg__c = SRB.Total_budget_kg__c;
            CityBudget.TotalBudgetRMB__c = SRB.Total_budget_RMB__c;
            SubregionName = SRB.Name.substring(SRB.Name.indexOf('年')+1,SRB.Name.indexOf('专业'));
            

            Decimal TotalLastYearPEShipmentValue = 0;

            Decimal TotalLastYearPEConversionValue = 0;
            Decimal TotalThisYearPEConversionValue = 0;
            Decimal TotalLastYearInMarketSalesValue = 0;
            Decimal TotalThisYearInMarketSalesValue = 0;

            List<InMarketSales__c> TotalLastYearInMarketSales = [Select Area__c,InMarketSaleskg__c, SalesCity__c From 
                                   InMarketSales__c Where InMarketSaleskg__c > 0 and Year__c =: integer.valueof(CityBudget.Year__c)-1 and  SubRegion__c =: SubregionName];                    
            for(InMarketSales__c t : TotalLastYearInMarketSales )
            {
                TotalLastYearInMarketSalesValue += (Decimal)t.InMarketSaleskg__c;
            }
            
            List<InMarketSales__c> TotalThisYearInMarketSales = [Select Area__c,InMarketSalesForcast__c,SalesCity__c From InMarketSales__c Where InMarketSalesForcast__c > 0 and Year__c =: integer.valueof(CityBudget.Year__c)  and  SubRegion__c =: SubregionName];
            for(InMarketSales__c t : TotalThisYearInMarketSales )
            {
                TotalThisYearInMarketSalesValue += (Decimal)t.InMarketSalesForcast__c;
            }

            List<AggregateResult> TotalLastYearPEConversion = [Select sum(PE_conversion_achieve__c)TotalIn  From 
                                  Achieve__c Where PE_conversion_achieve__c > 0 and   Year__c =: string.valueof(integer.valueof(CityBudget.Year__c)-1) and  subregion__c =: SubregionName ];
            List<AggregateResult> TotalThisYearPEConversion = [Select sum(PE_Conversion_forecast__c)TotalIn  From 
                                  Achieve__c Where PE_Conversion_forecast__c > 0 and   Year__c =: string.valueof(integer.valueof(CityBudget.Year__c)) and  subregion__c =: SubregionName ];

            TotalLastYearPEConversionValue = (Decimal)TotalLastYearPEConversion[0].get('TotalIn');
            TotalThisYearPEConversionValue = (Decimal)TotalThisYearPEConversion[0].get('TotalIn');
                                              
            List<Shipment__c > TotalLastYearPEShipment = [Select KG__c,SalesCity__c From Shipment__c Where KG__c > 0 and   Year__c =: integer.valueof(CityBudget.Year__c)-1 and SubRegion__c =: SubregionName and CalcInKg__c =: true];

            for(Shipment__c p : TotalLastYearPEShipment)
            {
                TotalLastYearPEShipmentValue += p.KG__c;
            }
            
            pList = [Select id,name,Area__r.name From Place__c Where PlaceType__c =: GlobalProperties.CityType and  Subregion__r.Name =: SubregionName order by Area__r.name];
           
            for(Place__c p : pList)
            {
                TableItemControl T = new TableItemControl();
                T.Str = p.name;
                T.Str1 = p.Area__r.name;
                
                Decimal SubRegionLastYearInMarketSalesValue = 0;
                Decimal SubRegionThisYearInMarketSalesValue = 0;
                for(InMarketSales__c tl : TotalLastYearInMarketSales )
                {
                    
                    if(p.Area__r.name == tl.SalesCity__c)
                    {
                        
                        SubRegionLastYearInMarketSalesValue += (Decimal)tl.InMarketSaleskg__c;
                    }
                }
                for(InMarketSales__c tl : TotalThisYearInMarketSales )
                {
                    if(p.Area__r.name == tl.SalesCity__c)
                    {
                        SubRegionThisYearInMarketSalesValue += (Decimal)tl.InMarketSalesForcast__c;
                    }
                }
                if(TotalLastYearInMarketSalesValue > 0) 
                    T.CB.LastYearSalesWeighting__c = SubRegionLastYearInMarketSalesValue / TotalLastYearInMarketSalesValue * 100;
                else
                    T.CB.LastYearSalesWeighting__c = 0;
                    
       
                List<AggregateResult> SubRegionLastYearPEConversion = [Select sum(PE_conversion_achieve__c)TotalIn  From 
                                      Achieve__c Where PE_conversion_achieve__c > 0 and   Year__c =: string.valueof(integer.valueof(CityBudget.Year__c)-1) and  Sales_city__c =: p.name];
                List<AggregateResult> SubRegionThisYearPEConversion = [Select sum(PE_Conversion_forecast__c)TotalIn  From 
                                      Achieve__c Where PE_Conversion_forecast__c > 0 and   Year__c =: string.valueof(integer.valueof(CityBudget.Year__c)) and  Sales_city__c =: p.name];

                if(TotalLastYearPEConversion.size() > 0){
                    if(((Decimal)TotalLastYearPEConversion[0].get('TotalIn') > 0) &&((Decimal)SubRegionLastYearPEConversion[0].get('TotalIn') > 0))
                        T.CB.LastYearConversionWeighting__c = (Decimal)SubRegionLastYearPEConversion[0].get('TotalIn') / (Decimal)TotalLastYearPEConversion[0].get('TotalIn') * 100;
                    else
                        T.CB.LastYearConversionWeighting__c = 0;
                }
                else
                {
                    T.CB.LastYearConversionWeighting__c = 0;
                }
                
                Decimal LastYearPEShipmentValue = 0;

                for(Shipment__c tl : TotalLastYearPEShipment )
                {
                    if(p.name == tl.SalesCity__c)
                    {
                        LastYearPEShipmentValue += (Decimal)tl.KG__c;
                    }
                }                    
 
                if(LastYearPEShipmentValue > 0)
                    T.CB.LastYearInMarketSalesKg__c = SubRegionLastYearInMarketSalesValue / LastYearPEShipmentValue;
                else
                    T.CB.LastYearInMarketSalesKg__c = 0;
                if((Decimal)SubRegionLastYearPEConversion[0].get('TotalIn')> 0)   
                    T.CB.LastYearPESampleKg__c = LastYearPEShipmentValue / (Decimal)SubRegionLastYearPEConversion[0].get('TotalIn');
                else
                    T.CB.LastYearPESampleKg__c = 0;             

                T.CB.InMarketValueHide__c =  SubRegionThisYearInMarketSalesValue;
                if(SubRegionThisYearPEConversion[0].get('TotalIn') != null)
                {

                    T.CB.ConversionForcast__c =  (Decimal)SubRegionThisYearPEConversion[0].get('TotalIn');                             
                }
                else
                    T.CB.ConversionForcast__c = 0;
                T.CB.ThisYearInMarketSaleskg__c = 0;
                T.CB.ThisYearPESamplekg__c = 0;   

                
                TableItemsDown.add(T);
            }
           List<AggregateResult> CalcExitCityBudget = [Select sum(c.TotalScore__c)tScore, sum(c.TotalBudgetkg__c)tKg, sum(c.TotalBudgetRMB__c)tRMB, sum(c.PotentialScore__c)pScore, sum(c.FinalWeighting__c)fWeight From CityBudget__c c Where c.SubRegionBudget__c =: UrlId ];
             
           TableItemControl TT = new TableItemControl();
           TT.Str = '总计';
           TT.InputPercent = 100;
           TT.CB.TotalScore__c = (Decimal)CalcExitCityBudget[0].get('tScore');
           TT.CB.TotalBudgetkg__c = (Decimal)CalcExitCityBudget[0].get('tKg');
           TT.CB.TotalBudgetRMB__c = (Decimal)CalcExitCityBudget[0].get('tRMB');
           TT.CB.PotentialScore__c = (double)CalcExitCityBudget[0].get('pScore');
           TT.CB.FinalWeighting__c = (double)CalcExitCityBudget[0].get('fWeight');
           
            if(TotalLastYearPEShipmentValue > 0) 
                TT.CB.LastYearInMarketSalesKg__c = TotalLastYearInMarketSalesValue / TotalLastYearPEShipmentValue ;
            else
                TT.CB.LastYearInMarketSalesKg__c = 0;
            if(TotalLastYearPEConversionValue > 0) 
                TT.CB.LastYearPESampleKg__c = TotalLastYearPEShipmentValue / TotalLastYearPEConversionValue ;
            else
                TT.CB.LastYearPESampleKg__c = 0;

            TT.CB.InMarketValueHide__c =  TotalThisYearInMarketSalesValue;
            TT.CB.ConversionForcast__c =  TotalThisYearPEConversionValue;
            TT.CB.ThisYearInMarketSaleskg__c = 0;
            TT.CB.ThisYearPESamplekg__c = 0;         
                     
           AmountBudget.add(TT);

           if(ExistRecord.size() >0)
           {
               if(ExistRecord[0].Approved__c == true)
               {
                    msg = '审批通过，不能再修改！';
                    DisplaySave = false;                
               }           
               if(cu.ProfileId == ProfileMarketing.id)
               {
                    if(ExistRecord[0].Submit__c){ 
                        msg = '已提交申请，不能再修改！';
                        DisplaySave = false;             
                    }
               }              
               if((cu.ProfileId == ProfileRSM.id)||(cu.ProfileId == ProfileRSTM.id))
               {
                    DisplayAdd = false;
                    DisplaySave = false;  
               }               
               for(CityBudget__c er : ExistRecord)
               {
                   for(TableItemControl tid : TableItemsDown)
                   {
                       if(er.name.substring(er.name.indexOf('年')+1,er.name.indexOf('专业')) == tid.Str)
                       {
                           tid.CB = er;
                           tid.Exist = true;
                       }
                   }
               }
               if(ExistRecordMultiple.size()>0)
               {
                   for(CityBudget__c er : ExistRecordMultiple)
                   {
                        TableItemControl T = new TableItemControl();
                        T.Str = er.SalesCity__c;
                        T.Str1 = er.Area__c;
                        T.CB =er;
                        T.Exist = true;
                        AddMoreBudget.add(T);
                   }
               }   
           } 
           else
           {
               if((cu.ProfileId != ProfileMarketing.id)&&(cu.ProfileId != ProfileSRMMM.id ))
               {
                    msg = '未提交城市分配，不能进行审批调整';
                    DisplaySave = false;                
               }             
           }
           
           
           if(AddMoreBudget.size() > 0)
               CityBudget.HaveOther__c = 1;
           else
               CityBudget.HaveOther__c = 0;
        }
        
    }
    
    // city options
    public List<SelectOption> options{
        get{
             if(options == null)
                options = new List<SelectOption>();
             else
                options.clear();
                
            for(Place__c p : pList)
            { 
                options.add(new SelectOption(p.Id,p.Name)); 
            }     
           return options;   
        }
        set;
    }


    public void SetRecord(Boolean Submit)
    {
        // set table items down
        List<CityBudget__c> InsertCityBudgetList = new List<CityBudget__c>();
        List<CityBudget__c> UpdateCityBudgetList = new List<CityBudget__c>();
        
        List<CityBudget__c> InsertCityBudgetOtherList = new List<CityBudget__c>();
        List<CityBudget__c> UpdateCityBudgetOtherList = new List<CityBudget__c>(); 
        
        List<Sub_Region_Budget__Share> SubRegionBudgetShare = new List<Sub_Region_Budget__Share>();   
        List<Id> CityHeadIds = new List<Id>();       
        
        
        for(TableItemControl t : TableItemsDown){
            if(t.CB.CityHead__c != null)
                CityHeadIds.add(t.CB.CityHead__c); // get city head id        
        }
        for(TableItemControl t : AddMoreBudget)
        {
            if(t.CB.CityHead__c != null)
                CityHeadIds.add(t.CB.CityHead__c); // get city head id          
        }
        
        List<User> CityHeadInfoList = [Select u.ManagerId, u.Id From User u Where id in:CityHeadIds];
        List<Id> RSMIds = new List<Id>();
        
        for(User u : CityHeadInfoList)
        {
            RSMIds.add(u.ManagerId);
        }
        List<User> RSMInfo = [Select id,ProfileId,ManagerId From User Where id in: RSMIds and (ProfileId =: ProfileRSM.id or ProfileId =: ProfileRSTM.id) Limit 1];
        
        for(TableItemControl t : TableItemsDown){
            // don't fill in data, jump
            /*
            if(((t.CB.TotalBudgetkg__c == null)&&(t.CB.PotentialScore__c == null)&&(t.CB.CityHead__c == null))||((t.CB.PotentialScore__c == 0)&&(t.CB.CityHead__c == null)))
                continue;
            */
            if(t.CB.TotalBudgetkg__c == null)
                t.CB.TotalBudgetkg__c = 0;
            if(t.CB.PotentialScore__c == null)
                t.CB.PotentialScore__c = 0;        
            t.CB.Year__c = CityBudget.Year__c;
            t.CB.Rate__c = CityBudget.Rate__c;
            if(t.CB.TotalBudgetkg__c > 0)
                t.CB.TotalBudgetRMB__c = t.CB.Rate__c * t.CB.TotalBudgetkg__c;
            else
            {
                t.CB.TotalBudgetkg__c = 0;
                t.CB.TotalBudgetRMB__c = 0;
            }
                

            t.CB.Approved__c = Submit;
            if(RSMInfo.size() > 0)
                t.CB.RGM__c = RSMInfo[0].ManagerId;
            if(RSMInfo.size() > 0)    
                t.CB.RSM__c = RSMInfo[0].id;
            if(t.CB.TotalBudgetkg__c > 0)
                t.CB.ThisYearInMarketSaleskg__c = t.CB.InMarketValueHide__c / t.CB.TotalBudgetkg__c;
            else
                t.CB.ThisYearInMarketSaleskg__c = 0 ;
            t.CB.ThisYearInMarketSaleskg__c = t.CB.ThisYearInMarketSaleskg__c.intValue();
            if(t.CB.ConversionForcast__c > 0)
                t.CB.ThisYearPESamplekg__c = t.CB.TotalBudgetkg__c / t.CB.ConversionForcast__c;
            else
                t.CB.ThisYearPESamplekg__c = 0;
            t.CB.ThisYearPESamplekg__c = t.CB.ThisYearPESamplekg__c.intValue();
            
            
            for(Place__c p : pList)
            {
                if(t.Str == p.name)
                {
                    t.CB.Place__c = p.id; // set place
                }
            }
            
            t.CB.Name = CityBudget.Year__c + '年' + t.str + '专业样品管理'; // create record name
            if(t.Exist == false){
                t.CB.SubRegionBudget__c = UrlId; 
                InsertCityBudgetList.add(t.CB);
            }
            else{
                UpdateCityBudgetList.add(t.CB);
            }
        }
        if(UpdateCityBudgetList.size() > 0)
            update UpdateCityBudgetList;
        if(InsertCityBudgetList.size() > 0)
            insert InsertCityBudgetList;
        
        // set Multiple city head budget                 
        if(AddMoreBudget.size() > 0){
            for(TableItemControl t : AddMoreBudget)
            {

                t.CB.Year__c = CityBudget.Year__c;
                t.CB.Rate__c = CityBudget.Rate__c;
                t.CB.TotalBudgetRMB__c = t.CB.Rate__c * t.CB.TotalBudgetkg__c;
                   
                t.CB.Approved__c = Submit;
                t.CB.Name = CityBudget.Year__c + '年' + t.str + '专业样品管理';
                t.CB.SubRegionBudget__c = UrlId;
                t.CB.Multiple__c = true;
                if(RSMInfo.size() > 0)
                    t.CB.RGM__c = RSMInfo[0].ManagerId;
                if(RSMInfo.size() > 0)    
                    t.CB.RSM__c = RSMInfo[0].id;
                if(t.CB.TotalBudgetkg__c > 0)
                    t.CB.ThisYearInMarketSaleskg__c = t.CB.InMarketValueHide__c / t.CB.TotalBudgetkg__c;
                else
                    t.CB.ThisYearInMarketSaleskg__c = 0;
                t.CB.ThisYearInMarketSaleskg__c = t.CB.ThisYearInMarketSaleskg__c.intValue();
                if(t.CB.ConversionForcast__c > 0)
                    t.CB.ThisYearPESamplekg__c = t.CB.TotalBudgetkg__c / t.CB.ConversionForcast__c;
                else
                    t.CB.ThisYearPESamplekg__c = 0;
                t.CB.ThisYearPESamplekg__c = t.CB.ThisYearPESamplekg__c.intValue();
                                                
                for(Place__c p : pList)
                {
                    if(t.Str == p.name)
                    {
                        t.CB.Place__c = p.id;
                    }
                }

                if(t.Exist == false)
                    InsertCityBudgetOtherList.add(t.CB); 
                else
                    UpdateCityBudgetOtherList.add(t.CB);                    
            } 
        }    
        if(InsertCityBudgetOtherList.size() > 0)
            insert InsertCityBudgetOtherList;
        if(UpdateCityBudgetOtherList.size() > 0)    
            Update UpdateCityBudgetOtherList;
        
        // share the sub region budget to city head
       if( cu.ProfileId == ProfileMarketing.id ){
            if(CityHeadIds.size() > 0)
            {
                for(Id owner : CityHeadIds){
                    Sub_Region_Budget__Share mShare = new Sub_Region_Budget__Share();
                    mShare.ParentId = SRB.id;
                    mShare.UserOrGroupId = owner;
                    mShare.AccessLevel = 'Read';
                    SubRegionBudgetShare.add(mShare);
                }
            }
            insert SubRegionBudgetShare;    

            // share the city budget to city head
            List<CityBudget__Share> CityBudgetShare = new List<CityBudget__Share>();
            List<CityBudget__Share> DelCityBudgetShare = new List<CityBudget__Share>();
            List<Id> DelIds = new List<Id>();
            for(CityBudget__c c : InsertCityBudgetList){
                CityBudget__Share mShare = new CityBudget__Share();
                mShare.ParentId = c.id;
                mShare.UserOrGroupId = c.CityHead__c;
                mShare.AccessLevel = 'Read';
                CityBudgetShare.add(mShare);
            }  
            for(CityBudget__c c : UpdateCityBudgetList){
                CityBudget__Share mShare = new CityBudget__Share();
                mShare.ParentId = c.id;
                mShare.UserOrGroupId = c.CityHead__c;
                mShare.AccessLevel = 'Read';
                CityBudgetShare.add(mShare);
            }      
            for(CityBudget__c c : UpdateCityBudgetOtherList){
                CityBudget__Share mShare = new CityBudget__Share();
                mShare.ParentId = c.id;
                mShare.UserOrGroupId = c.CityHead__c;
                mShare.AccessLevel = 'Read';
                CityBudgetShare.add(mShare);
                DelIds.add(c.id);        
            } 
            DelCityBudgetShare = [Select id From CityBudget__Share Where id in: DelIds];
            
            for(CityBudget__c c : InsertCityBudgetOtherList){
                CityBudget__Share mShare = new CityBudget__Share();
                mShare.ParentId = c.id;
                mShare.UserOrGroupId = c.CityHead__c;
                mShare.AccessLevel = 'Read';
                CityBudgetShare.add(mShare);        
            } 
            if(DelCityBudgetShare.size() > 0)
                delete DelCityBudgetShare ; 
            if(CityBudgetShare.size() > 0)             
                insert CityBudgetShare;
            
        }    
    }


    public PageReference Save()
    {
        try
        {

            if(SRB.ApprovalStatusFormula__c != '审批通过')
            {
                pageReference pr = new pageReference('/'+ UrlId);     
                pr.setredirect(true);      
                return pr;
            }
    
            Decimal AllocatedNum = 0;     
            
            for(TableItemControl t : TableItemsDown){
                if((t.CB.TotalBudgetkg__c != null)&&(t.CB.TotalBudgetkg__c > 0)){
                    if((AllocatedNum == null)||(AllocatedNum == 0))
                        AllocatedNum = t.CB.TotalBudgetkg__c;
                    else
                        AllocatedNum += t.CB.TotalBudgetkg__c;
                }
                if(t.CB.CityHead__c == null)
                {
                    msg = '城市经理未填写完整！';
                    return null;            
                }
            }
            if(AddMoreBudget.size() > 0){
                for(TableItemControl t : AddMoreBudget){
                    if((t.CB.TotalBudgetkg__c != null)&&(t.CB.TotalBudgetkg__c > 0)){
                        if((AllocatedNum == null)||(AllocatedNum == 0))
                            AllocatedNum = t.CB.TotalBudgetkg__c;
                        else
                            AllocatedNum += t.CB.TotalBudgetkg__c;
                    }
                }        
            }        
            if(AllocatedNum != CityBudget.TotalBudgetkg__c)
            {
                msg = '分配公斤数应等于分配到片区的预算公斤数';
                return null;
            }         
            
            
            if(AddMoreBudget.size() > 0){
                // city head repeat between AddMoreBudget and TableItemsDown
                for(TableItemControl amb : AddMoreBudget)
                {
                    for(TableItemControl t : TableItemsDown){
                        if((amb.CB.CityHead__c == t.CB.CityHead__c)&&(amb.Str == t.Str))
                        {
                            msg = amb.Str + '城市经理重复，请修改！';
                            return null;
                        }
                    }
                }
                // city head repeat in AddMoreBudget
                for(TableItemControl ti: AddMoreBudget)
                {
                    Boolean Second = false;
                    for(TableItemControl t : AddMoreBudget){
                        if((ti.Str == t.Str)&&(Second == false)&&(ti.CB.CityHead__c == t.CB.CityHead__c))
                        {
                            Second = true;
                            continue;
                        }
                        if((ti.CB.CityHead__c == t.CB.CityHead__c)&&(ti.Str == t.Str)&&(Second == true))
                        {
                            msg = ti.Str + '城市经理重复，请修改！';
                            return null;
                        }
                    }
                }            
            }
           
            SetRecord(false);
                    
            pageReference pr = new pageReference('/'+ UrlId);     
            pr.setredirect(true);      
            return pr;
        }
        catch (DmlException e) {
            ApexPages.addMessages(e);
            return null;
         }         
    }
    public PageReference Remove()
    {
        List<CityBudget__c> deleteCB = new List<CityBudget__c>();
        List<TableItemControl> NewAddMoreBudget = new List<TableItemControl>();
        for(TableItemControl t : AddMoreBudget)
        {
            if(t.Check == false)
            {
                NewAddMoreBudget.add(t);
            }
            else
            {
                if(t.Exist == true)
                {
                    deleteCB.add(t.CB);
                }
            }
        }
        AddMoreBudget.clear();
        AddMoreBudget =  NewAddMoreBudget;
        delete deleteCB;   
 
           if(AddMoreBudget.size() > 0)
               CityBudget.HaveOther__c = 1;
           else
               CityBudget.HaveOther__c = 0;
                       
        return null;
    }    
    
    public void Add()
    {
    
        TableItemControl T = new TableItemControl();
        Place__c get =  [Select Id,Name,Area__r.name From Place__c Where id =: IdSelect];

        T.Str = get.name;
        T.Str1 = get.Area__r.name;
        T.Exist = false;
        
        Integer recordNum = 1;
        Double totalCityKg = 0;
        for(TableItemControl ta : AddMoreBudget){
            if(ta.Str == T.Str)
            {
                recordNum++;
                if(ta.CB.TotalBudgetkg__c > 0 ){
                    totalCityKg += ta.CB.TotalBudgetkg__c;
                }
            }
        }
        
        for(TableItemControl ta : TableItemsDown){
            if(ta.Str == T.Str)
            {
                T.CB.InMarketValueHide__c = ta.CB.InMarketValueHide__c;
                T.CB.ConversionForcast__c = ta.CB.ConversionForcast__c;
                T.CB.LastYearInMarketSalesKg__c = ta.CB.LastYearInMarketSalesKg__c;
                T.CB.LastYearPESampleKg__c = ta.CB.LastYearPESampleKg__c;
                T.CB.LastYearConversionWeighting__c = ta.CB.LastYearConversionWeighting__c;
                T.CB.LastYearSalesWeighting__c = ta.CB.LastYearSalesWeighting__c;
                                            
               recordNum++;
               if(ta.CB.TotalBudgetkg__c > 0 )
               {
                   totalCityKg += ta.CB.TotalBudgetkg__c;              
               }
            }  
        }
        Double AddCityKg = 0;
        for(TableItemControl ta : TableItemsDown){
            if(ta.Str == T.Str)
            {
                ta.CB.TotalBudgetkg__c = totalCityKg / recordNum;
                ta.CB.TotalBudgetkg__c = ta.CB.TotalBudgetkg__c.longValue();
                AddCityKg += ta.CB.TotalBudgetkg__c;              

            }  
        }      
        for(TableItemControl ta : AddMoreBudget){
            if(ta.Str == T.Str)
            {
                ta.CB.TotalBudgetkg__c = totalCityKg / recordNum;
                ta.CB.TotalBudgetkg__c = ta.CB.TotalBudgetkg__c.longValue();
                AddCityKg += ta.CB.TotalBudgetkg__c; 

            }
        }
                  
        T.CB.TotalBudgetkg__c = totalCityKg - AddCityKg;
        if(T.CB.TotalBudgetkg__c > 0)
            T.CB.ThisYearInMarketSaleskg__c = T.CB.InMarketValueHide__c /T.CB.TotalBudgetkg__c;
        else
            T.CB.ThisYearInMarketSaleskg__c = 0;
        if(T.CB.ConversionForcast__c > 0)    
            T.CB.ThisYearPESamplekg__c = T.CB.TotalBudgetkg__c/T.CB.ConversionForcast__c;
        else
            T.CB.ThisYearPESamplekg__c = 0;           
        
        AddMoreBudget.add(T); 
           if(AddMoreBudget.size() > 0)
               CityBudget.HaveOther__c = 1;
           else
               CityBudget.HaveOther__c = 0;               
    }

            
    public PageReference Cancel()
    {
        pageReference pr = new pageReference('/'+ UrlId);     
        pr.setredirect(true);      
        return pr;
    }
    private final ApexPages.StandardController controller;
    
    static testMethod void OverrideViewTest()
    {
       Profile p  = [select id from profile where name =: GlobalProperties.ProfileRMMM  ];
        UserRole SRMMM_SOC = [Select Id,Name From UserRole Where Name =: GlobalProperties.SRMMM_SOC];
        
        User u1 = new User (alias = 'standt', email = 'shuaicao@isoftstone.com', emailencodingkey='UTF-8',UserRoleId = SRMMM_SOC.id,
                lastname = 'Testing', languagelocalekey = 'en_US', localesidkey='en_US', Title__c = 'Sales Rep',profileid = p.id, 
                timezonesidkey = 'America/Los_Angeles', username='asdfdaa@testorg1.com');
        insert u1;
        
        System.runAs(u1) {
            PE_Sample_Management__c PE = new PE_Sample_Management__c();
            PE.WOC_Total_budget_RMB__c = 1;
            PE.Deal__c = true;
            PE.WOC_budget_allocation_kg__c = 2;
            PE.WOCInMarketValueHide__c = 0;
            PE.WOCConversionForcast__c = 0;                  
            PE.SOC_Total_budget_RMB__c = 0;
            PE.SOC_budget_allocation_kg__c = 0;
            PE.SOCInMarketValueHide__c = 0;
            PE.SOCConversionForcast__c = 0;                  
            PE.EOC_Total_budget_RMB__c = 0;
            PE.EOC_budget_allocation_kg__c = 0;
            PE.EOCInMarketValueHide__c = 0;
            PE.EOCConversionForcast__c = 0;            
            PE.NOC_Total_budget_RMB__c = 0;
            PE.NOC_budget_allocation_kg__c = 0;
            PE.NOCInMarketValueHide__c = 0;
            PE.NOCConversionForcast__c = 0;
            PE.Rate__c =2;
            PE.Total_Budget_Allocation_RMB__c = 1;
            insert PE;
            
            RegionalBudget__c RB = new RegionalBudget__c();
            RB.PESampleManagement__c = PE.id;
            RB.Approved__c = true;
            RB.ApprovalStatus__c = '审批通过';
            insert RB;
            
            Sub_Region_Budget__c SRB = new Sub_Region_Budget__c();
            SRB.PE_Sample_Management__c = PE.id;
            SRB.RegionalBudget__c = RB.id;
            SRB.Name = '2012年华南一区专业样品管理';
            insert SRB;
            
            test.setCurrentPageReference(Page.OverrideSubRegionBudgetNew);
            System.currentPageReference().getParameters().put('id', SRB.Id);          
            
            OverrideCityBudgetNew testCase = new OverrideCityBudgetNew();
            Profile pASM  = [select id from profile where name =: GlobalProperties.ProfileASM ];
            List<User> CH = [Select id,ManagerId From User Where profileId =: pASM.id  and IsActive =: true ];
            
            for(TableItemControl t : testCase.TableItemsDown){
                t.CB.CityHead__c = CH[0].id;  
            }            

            testCase.Save();
            testCase.Remove();
            testCase.Cancel();

            
        
        }             
    }
 
}